import { getDictList, getMenus, getUserInfo } from "@/api/common";
import { listToMenuTree } from "@/utils";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "..";

const initialState = {
  user_info: {} as UserInfo,
  sysMenus: [] as SysMenuType[],
  menus: [] as MenuItem[],
  dict: {} as DictInfoType,
};

export const get_user_info = createAsyncThunk<UserInfo>(
  "get/get_user_info",
  async () => {
    return await getUserInfo();
  }
);
export const get_user_menus = createAsyncThunk<SysMenuType[]>(
  "get/get_user_menus",
  async () => {
    return await getMenus();
  }
);

export const get_dict_info = createAsyncThunk<DictInfoType, Array<String>>(
  "get/get_dict_info",
  async (action) => {
    return await getDictList(action);
  }
);

const appSlice = createSlice({
  name: "app",
  initialState,
  reducers: {
    // 定义reducer函数
    set_user_info: (state, action) => {
      state.user_info = action.payload;
    },
  },
  extraReducers(builder) {
    builder
      .addCase(get_user_info.fulfilled, (state, action) => {
        state.user_info = action.payload;
      })
      .addCase(get_user_menus.fulfilled, (state, action) => {
        state.sysMenus = action.payload;
        state.menus = listToMenuTree(action.payload);
      })
      .addCase(get_dict_info.fulfilled, (state, action) => {
        state.dict = action.payload;
      });
  },
});

export const selectUserInfo = (state: RootState) => state.app.user_info;
export const selectUserMenus = (state: RootState) => state.app.menus;
export const selectUserSysMenus = (state: RootState) => state.app.sysMenus;
export const selectDict = (state: RootState) => state.app.dict;

export const { set_user_info } = appSlice.actions;

export default appSlice.reducer;
